import React, { useState, useEffect } from "react";
import "../../../assets/style/Home/index.scss";
import {
  Layout,
  Space,
  Table,
  Button,
  Dropdown,
  Input,
  Modal,
  Form,
  message,
} from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import {
  getStudentList,
  getStudentById,
  getStudentByClass,
  getClassList,
  postCreateClass,
  postCreateStudent,
  postModifyStudent,
  postdeleteStudent,
  postdeleteStudentClass,
} from "../../../service/student.service";
const { Search } = Input;

const { Header, Content } = Layout;

const StudentManage = () => {
  const [modal, contextHolder] = Modal.useModal();

  const [create_class_open, set_create_class_open] = useState(false);
  const [create_student_open, set_create_student_open] = useState(false);
  const [edit_student_open, set_edit_student_open] = useState(false);
  const [edit_student_info, set_edit_student_info] = useState(null);
  const [create_class_confirmLoading, set_create_class_confirmLoading] =
    useState(false);
  const [create_student_confirmLoading, set_create_student_confirmLoading] =
    useState(false);
  const [edit_student_confirmLoading, set_edit_student_confirmLoading] =
    useState(false);
  const [table_data, set_table_data] = useState(null);
  const [items, set_items] = useState(null);

  const [form] = Form.useForm();

  const onClick = ({ key }) => {
    // console.log(`Click on item ${key}`);
    refresh_table_byClass(key);
  };
  const onSearch = (value) => {
    console.log(value);
    if (value) refresh_table_byId(value);
    else if (value === "") refresh_table();
  };

  const hide_create_class_Modal = () => {
    set_create_class_open(false);
  };

  const hide_create_student_Modal = () => {
    set_create_student_open(false);
  };

  const hide_edit_student_Modal = () => {
    set_edit_student_open(false);
  };

  const create_class_handle = (values) => {
    // console.log("Success:", values);
    set_create_class_confirmLoading(true);
    postCreateClass({
      id: 0,
      name: values.classname,
      majorId: parseInt(values.major),
      stuNum: 0,
      teacherId: parseInt(values.teacher),
    })
      .then((res) => {
        console.log(res);
        message.success("创建成功");
        set_create_class_open(false);
        set_create_class_confirmLoading(false);
      })
      .catch((err) => {
        console.error(err);
        message.error("创建失败");
        set_create_class_open(false);
        set_create_class_confirmLoading(false);
      });
  };
  const create_class_handle_Failed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const create_student_handle = (values) => {
    set_create_student_confirmLoading(true);
    postCreateStudent({
      id: null,
      name: values.name,
      majorId: parseInt(values.majorId),
      classId: parseInt(values.classId),
      age: parseInt(values.age),
      sex: values.sex,
      account: values.account,
      password: values.password,
      type: "0",
    })
      .then((res) => {
        console.log(res);
        message.success("添加成功");
        refresh_table();
        set_create_student_open(false);
        set_create_student_confirmLoading(false);
      })
      .catch((err) => {
        console.error(err);
        message.error("添加失败");
        set_create_student_open(false);
        set_create_student_confirmLoading(false);
      });
  };
  const create_student_handle_Failed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const edit_student_handle = (values) => {
    set_edit_student_confirmLoading(true);
    postModifyStudent({
      id: edit_student_info.id,
      name: values.name,
      majorId: parseInt(values.majorId),
      classId: parseInt(values.classId),
      age: parseInt(values.age),
      sex: values.sex,
      account: values.account,
      password: values.password,
      type: "1",
    })
      .then((res) => {
        console.log(res);
        message.success("修改成功");
        refresh_table();
        set_edit_student_open(false);
        set_edit_student_confirmLoading(false);
      })
      .catch((err) => {
        console.error(err);
        message.error("修改失败");
        set_edit_student_open(false);
        set_edit_student_confirmLoading(false);
      });
  };
  const edit_student_handle_Failed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  const delete_student_confirm = (delete_id) => {
    modal.confirm({
      title: "删除确定",
      icon: <ExclamationCircleOutlined />,
      content: "是否确认删除该学生",
      okText: "删除",
      cancelText: "取消",
      onOk() {
        postdeleteStudent(delete_id)
          .then((res) => {
            console.log(res);
            refresh_table();
          })
          .catch((err) => {
            console.error(err);
          });
      },
    });
    // 调用删除接口，删除完重新刷新表格
  };
  const delete_student_from_class_confirm = (delete_id, delete_classId) => {
    modal.confirm({
      title: "退出确定",
      icon: <ExclamationCircleOutlined />,
      content: "是否确认退出班级",
      okText: "删除",
      cancelText: "取消",
      onOk() {
        postdeleteStudentClass(delete_id, parseInt(delete_classId))
          .then((res) => {
            console.log(res);
            refresh_table();
          })
          .catch((err) => {
            console.error(err);
          });
      },
    });
    // 调用删除接口，删除完重新刷新表格
  };
  const columns = [
    {
      title: "学生ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "专业",
      dataIndex: "majorId",
      key: "major",
    },
    {
      title: "班级",
      dataIndex: "classId",
      key: "class",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              getStudentInfo(record.id);
            }}
          >
            详细
          </a>
          <a
            onClick={() => {
              delete_student_confirm(record.id);
            }}
          >
            删除学生
          </a>
          <a
            onClick={() => {
              delete_student_from_class_confirm(record.id, record.classId);
            }}
          >
            退出班级
          </a>
        </Space>
      ),
    },
  ];

  // 点击某个学生的详细之后  加载该学生的信息
  const getStudentInfo = (edit_student_id) => {
    getStudentById(edit_student_id)
      .then((res) => {
        if (res.studentList[0]) {
          set_edit_student_info(res.studentList[0]);
          form.setFieldsValue(res.studentList[0]);
          console.log(res.studentList[0]);
        }
        set_edit_student_open(true);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  // 初始化
  useEffect(() => {
    /* 
        加载全部表格
        加载全部班级
    */
    refresh_table();
    refresh_class();
  }, []);

  const refresh_table_byId = (find_student) => {
    getStudentById(find_student)
      .then((res) => {
        set_table_data(res.studentList);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  const refresh_table_byClass = (find_class) => {
    getStudentByClass(find_class)
      .then((res) => {
        set_table_data(res.studentList);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  const refresh_table = () => {
    getStudentList()
      .then((res) => {
        console.log(res);
        set_table_data(res.studentList);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  const refresh_class = () => {
    getClassList()
      .then((res) => {
        console.log(res);
        let classId_arr = [];
        res.clazzList.forEach((item) => {
          classId_arr.push({ key: item.id + "", label: item.id + "" });
        });
        console.log(classId_arr);
        set_items(classId_arr);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  return (
    <div id="Home_page">
      <Space
        direction="vertical"
        style={{
          width: "100%",
        }}
        size={[0, 48]}
      >
        <Layout>
          <Header>学生管理</Header>
          <Content>
            <div className="operation_line">
              <Space size="middle">
                <Search
                  placeholder="输入学生ID"
                  onSearch={onSearch}
                  style={{
                    width: 200,
                  }}
                />
                <Dropdown
                  menu={{
                    items,
                    onClick,
                  }}
                  placement="bottomLeft"
                >
                  <Button>选择班级</Button>
                </Dropdown>
              </Space>
              <Space size="middle">
                <Button
                  type="primary"
                  onClick={() => {
                    set_create_student_open(true);
                  }}
                >
                  添加学生
                </Button>
                <Button
                  onClick={() => {
                    set_create_class_open(true);
                  }}
                >
                  创建班级
                </Button>
              </Space>
            </div>
            <Table
              columns={columns}
              dataSource={table_data}
              pagination={{ defaultPageSize: 10 }}
            />
          </Content>
        </Layout>
      </Space>
      <div className="Modal_container">
        {/* 创建班级 */}
        <Modal
          title="创建班级"
          open={create_class_open}
          footer={null}
          onCancel={hide_create_class_Modal}
          confirmLoading={create_class_confirmLoading}
          okText="创建"
          cancelText="取消"
        >
          <Form
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              maxWidth: 600,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={create_class_handle}
            onFinishFailed={create_class_handle_Failed}
            autoComplete="off"
          >
            <Form.Item
              label="所属专业"
              name="major"
              rules={[
                {
                  required: true,
                  message: "请输入班级专业",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="班级名称"
              name="classname"
              rules={[
                {
                  required: true,
                  message: "请输入班级名称",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="班级老师"
              name="teacher"
              rules={[
                {
                  required: true,
                  message: "请输入班级老师",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button
                type="primary"
                htmlType="submit"
                loading={create_class_confirmLoading}
              >
                确定创建
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        {/* 添加学生 */}
        <Modal
          title="添加学生"
          open={create_student_open}
          onOk={hide_create_student_Modal}
          onCancel={hide_create_student_Modal}
          okText="确认"
          cancelText="取消"
          footer={null}
        >
          <Form
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              maxWidth: 600,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={create_student_handle}
            onFinishFailed={create_student_handle_Failed}
            autoComplete="off"
          >
            <Form.Item
              label="姓名"
              name="name"
              rules={[
                {
                  required: true,
                  message: "请输入学生姓名",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="专业"
              name="majorId"
              rules={[
                {
                  required: true,
                  message: "请输入学生专业",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="班级"
              name="classId"
              rules={[
                {
                  required: true,
                  message: "请输入学生班级",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="年龄"
              name="age"
              rules={[
                {
                  required: true,
                  message: "请输入学生年龄",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="性别"
              name="sex"
              rules={[
                {
                  required: true,
                  message: "请输入学生性别",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="账号"
              name="account"
              rules={[
                {
                  required: true,
                  message: "请输入学生账号",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: "请输入学生密码",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button
                type="primary"
                htmlType="submit"
                loading={create_student_confirmLoading}
              >
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        {/* 编辑学生 */}
        <Modal
          title="编辑学生"
          open={edit_student_open}
          onOk={hide_edit_student_Modal}
          onCancel={hide_edit_student_Modal}
          okText="确认"
          cancelText="取消"
          footer={null}
        >
          <Form
            name="basic"
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 16,
            }}
            style={{
              maxWidth: 600,
            }}
            initialValues={{
              remember: true,
            }}
            onFinish={edit_student_handle}
            onFinishFailed={edit_student_handle_Failed}
            autoComplete="off"
            form={form}
          >
            <Form.Item
              label="姓名"
              name="name"
              rules={[
                {
                  required: true,
                  message: "请输入学生姓名",
                },
              ]}
            >
              <Input defaultValue={edit_student_info?.name} />
            </Form.Item>

            <Form.Item
              label="专业"
              name="majorId"
              rules={[
                {
                  required: true,
                  message: "请输入学生专业",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="班级"
              name="classId"
              rules={[
                {
                  required: true,
                  message: "请输入学生班级",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="年龄"
              name="age"
              rules={[
                {
                  required: true,
                  message: "请输入学生年龄",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="性别"
              name="sex"
              rules={[
                {
                  required: true,
                  message: "请输入学生性别",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="账号"
              name="account"
              rules={[
                {
                  required: true,
                  message: "请输入学生账号",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[
                {
                  required: true,
                  message: "请输入学生密码",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Button
                type="primary"
                htmlType="submit"
                loading={edit_student_confirmLoading}
              >
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      {contextHolder}
    </div>
  );
};

export default StudentManage;
